package com.jinlia.show.modules.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jinlia.show.modules.base.system.entity.SysUserRole;
import com.jinlia.show.modules.base.system.service.SysUserRoleMapperService;
import com.jinlia.show.modules.system.service.ifc.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysUserRoleService extends SysUserRoleMapperService implements ISysUserRoleService {
    /**
     * 保存用户角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    @Transactional
    public boolean saveUserRoles(Long userId, List<Long> roleIds) {
        if (userId == null || CollectionUtils.isEmpty(roleIds)) {
            return false;
        }
        //删除原用户角色
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleLambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
        this.remove(sysUserRoleLambdaQueryWrapper);
        //新增用户角色
        List<SysUserRole> saveUserRoles = roleIds.stream()
                .map(roleId -> new SysUserRole(userId, roleId))
                .collect(Collectors.toList());
        for (SysUserRole saveUserRole : saveUserRoles) {
            this.save(saveUserRole);
        }
//        this.saveBatch(saveUserRoles);
        return true;

    }

    /**
     * 判断角色是否存在绑定的用户
     *
     * @param roleId 角色ID
     * @return true：已分配 false：未分配
     */
    @Override
    public boolean hasAssignedUsers(Long roleId) {
//        int count = this.baseMapper.countUsersForRole(roleId);
//        return count > 0;
        return true;
    }

}
